package com.cpit.platform.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.utils.HttpClientUtil;
import com.cpit.platform.dao.SubSystemRepository;
import com.cpit.platform.dto.SubSystem;
import com.cpit.platform.log.LogOperator;

@Service
public class SubSystemStateChecking {

	private final String loggerName = this.getClass().getName();
	
	@Autowired
	private SubSystemRepository srep = null;
	
	public SubSystemStateChecking() {
		
	}
	
	@Scheduled(cron="0 0/10 * * * *")
	public void check() {
		LogOperator.info(loggerName, "check start");
		List<SubSystem> allSs = srep.findAll();
		LogOperator.debug(loggerName, "all sub system are: " + allSs);
		if(allSs != null && allSs.size() > 0) {
			HttpClientUtil hcu = new HttpClientUtil();
			for(SubSystem ss : allSs) {
				String ret = hcu.get(ss.getLoginUrl());
				LogOperator.debug(loggerName, "subsystem checking result: " + ss.getName() + "\n" + ret);
				if(ret == null || ret.length() == 0) {
					LogOperator.warn(loggerName, "subsystem is down: " + ss.getName());
					ss.setStatus(SystemConstant.SUBSYSTEM_STATUS_DOWN);
					srep.save(ss);
				} else {
					LogOperator.info(loggerName, "subsystem is running: " + ss.getName());
					ss.setStatus(SystemConstant.SUBSYSTEM_STATUS_RUNNING);
					srep.save(ss);
				}
			}
		}
	}
}
